/*
 * Activity.cpp
 *
 *  Created on: 17.02.2011
 *      Author: dis
 */
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include "Activity.h"

void Activity::toJSON(char* buffer, int size) {
	if (buffer == 0 || size < 1) {
		return;
	}
	char* current = buffer;

	if (subActivity != 0) {
		static char tmp[8 * 1024];
		subActivity->toJSON(tmp, 8 * 1024);
		snprintf(buffer, size,
				"{'id':%i,'time':%d,'type':%i,'name':'%s','sub':%s}", id,
				timestamp,type, name, tmp);
	} else {
		snprintf(buffer, size, "{'id':%i,'time':%d,'type':%i,'name':'%s'}", id,
				timestamp,type, name);
	}
}

Activity::Activity(unsigned long id, char* aName, unsigned long timestamp,
		int type) :
	subActivity(0) {
	this->id = id;
	this->timestamp = timestamp;
	this->type = type;
	name = 0;
	setName(aName);
}
Activity::Activity(unsigned long id, char* aName, unsigned long timestamp,
		int type, Activity* subActivity) {
	this->id = id;
	this->timestamp = timestamp;
	this->type = type;
	name = 0;
	setName(aName);
	this->subActivity = subActivity;
}

Activity* Activity::clone() {
	Activity* subTmp = 0;
	if (subActivity != 0) {
		subTmp = subActivity->clone();
	}
	Activity* tmp = new Activity(id, name, timestamp, type, subTmp);
	return tmp;
}

bool Activity::equals(Activity* obj) {
	if (obj == 0) {
		return false;
	}
	if (this == obj) {
		return true;
	}
	if (id == obj->id && type == obj->type
	// Name
			&& (name == obj->name || (name != 0 && obj->name != 0 && strcmp(
					name, obj->name) == 0))
	// Sub
			&& (subActivity == obj->subActivity || (subActivity != 0
					&& subActivity->equals(obj->subActivity)))) {
		return true;
	}
	return false;
}
void Activity::setName(char* value) {
	if (name != 0) {
		free(name);
		name = 0;
	}
	if (value != 0) {
		int len = strlen(value);
		name = (char*) malloc(len + 1);
		memset(name, 0, len + 1);
		strcpy(name, value);
		while (char* c = strchr(name, '\'')) {
			*c = '_';
		}
		while (char* c = strchr(name, '&')) {
			*c = '_';
		}
	}
}

Activity::~Activity() {
	setName(0);
	if (subActivity != 0) {
		delete subActivity;
	}
}
